<?php
/**
 * 商品抢购的后台逻辑
 * User: Jack
 * Date: 2020/12/18 0018
 * Time: 上午 9:38
 */

$id = $_GET['id'];

$link = mysqli_connect('localhost','root','root','shop') or die('数据库连接失败');

if( !mysqli_set_charset($link,'utf8') ){
    exit('字符集设置失败！');
}

set_exception_handler(function(Exception $e) use ($link){
    echo $e->getMessage();
    mysqli_query($link,'rollback');
});

# 查询 goods表 某件（id）商品的库存
$sql = "select stock from goods where goods_id = $id";
$result = mysqli_query($link,$sql);

if( !$result || mysqli_num_rows($result) == 0 ){
    throw new Exception('没有找到对应商品id',100);
}

$row = mysqli_fetch_assoc($result);
$stock = $row['stock'];
if( $stock > 0 ):
    # 生成订单
    $orderno = 'JD'.date('Ymd').mt_rand(10000,99999);
    $time = date('Y-m-d H:i:s');
    $sql = "insert into `order`(`orderno`,`created_at`) value('{$orderno}','{$time}')";
    $result = mysqli_query($link,$sql);

    if( !$result || mysqli_affected_rows($link) == 0 ){
        throw new Exception('订单生成失败',101);
    }

    # 更新库存
    $sql = "update goods set stock=stock-1 where goods_id = $id";
    $result = mysqli_query($link,$sql);
    if( !$result || mysqli_affected_rows($link) == 0 ){
        throw new Exception('更新失败',101);
    }

    mysqli_query($link,'commit');
    # 抢购成功
    header('location:success.html');
    exit;
else:
    header('location:fail.html');
endif;